package com.wangxiaoxuan.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.wangxiaoxuan.seckill.pojo.Order;
import com.wangxiaoxuan.seckill.pojo.SeckillOrder;
import com.wangxiaoxuan.seckill.pojo.User;
import com.wangxiaoxuan.seckill.service.IGoodsService;
import com.wangxiaoxuan.seckill.service.IOrderService;
import com.wangxiaoxuan.seckill.service.ISeckillOrderService;
import com.wangxiaoxuan.seckill.vo.GoodsVo;
import com.wangxiaoxuan.seckill.vo.ResBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 王小轩
 * @version 1.0
 * 秒杀controller
 */
@Controller
@RequestMapping("/secKill")
public class SecKillController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @RequestMapping("/doSecKill")
    public String doSecKill(Model model, User user,Long goodsId){
        //如果用户为空重定向至登录页面
        if (user == null){
            return "redirect:/login/toLogin";
        }
        //存在则存起来
        model.addAttribute("user",user);
        //在后台判断库存
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if ((goodsVo.getStockCount()<1)){
            //跳转失败页面
            model.addAttribute("errmsg", ResBeanEnum.EMPTY_STOCK.getMessage());
            return "secKillFail";
        }
        //判断订单
        SeckillOrder seckillOrder =
                seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        if(seckillOrder!=null){
            //订单不为空说明该用户抢过了
            model.addAttribute("errmsg",ResBeanEnum.REPEAT_ERROR);
            return "secKillFail";
        }
        //抢购
        Order order=orderService.seckill(user,goodsVo);//秒杀生成订单
        model.addAttribute("order",order);//放入
        model.addAttribute("goods",goodsVo);//放入物品
        return "orderDetail";
    }

}
